import {setCartList, getCartList, removeCartList} from '@/utils/cartList'
import {insertCartAPI,updateCartAPI, findNewCartListAPI, deleteCartAPI} from '@/api/cart'
import user from '../user'

const state = {
    cartList: JSON.parse(getCartList()) || [],
}
const actions = {
    // 添加购物车
    async addCart({dispatch, state}, goods) {
            // 登录之后的加入购物车逻辑
            await insertCartAPI(goods.id, goods.count);
            removeCartList()
            // 获取新购物车数据
            dispatch('getNewCartList')

    },
    // 删除购物车
    async deleteCart({dispatch}, cardId) {
        // 登录的删除购物车逻辑---调用接口实现接口购物车的删除功能
        await deleteCartAPI(cardId)
        // 获取新购物车数据
        dispatch('getNewCartList')

    },
    // 更新购物车
    async updateCart({dispatch}, card) {
        // 登录的删除购物车逻辑---调用接口实现接口购物车的删除功能
        await updateCartAPI(card)
        // 获取新购物车数据
        dispatch('getNewCartList')
    },
    // 清除购物车
    clearCart({state}) {
        state.cartList = []
    },
    // 单选功能
    singleCheck({commit}, {skuId, selected}) {
        commit('SINGLECHECK', {skuId, selected})
        setCartList(state.cartList)
    },
    // 全选功能
    allCheck({commit}, selected) {
        commit('ALLCHECK', selected)
        setCartList(state.cartList)
    },
    // 获取gwc列表
    async getNewCartList({commit}) {
        if (user.state.userInfo.id!=undefined){
            let res = await findNewCartListAPI();
            commit('GETNEWCARTLIST', res.data);
        }
    },
    // 合并购物车接口

}
const mutations = {
    SINGLECHECK(state, {skuId, selected}) {
        let idx = state.cartList.findIndex(item => item.id === skuId)
        state.cartList[idx].selected = selected;
    },
    ALLCHECK(state, selected) {
        state.cartList.forEach(item => {
            item.selected = selected;
        })
    },
    GETNEWCARTLIST(state, cartList) {
        state.cartList = cartList;
    }
}
const getters = {
    // 总数量
    allCount(state) {
        let count = 0;
        state.cartList?.forEach(item => {
            count += item.count;
        })
        return count;
    },
    // 总价
    allPrice(state) {
        let price = 0;
        state.cartList?.forEach(item => {
            price += item.count * item.price;
        })
        return price;
    },
    // 全选
    isAll(state) {
        return state.cartList?.every(item => {
            return item.selected === true;
        }) || false
    },
    // 已选总数量
    selectedCount(state) {
        return state.cartList?.filter(item => item.selected).reduce((sum, cur) => sum + cur.count, 0) || 0;
    },
    // 已选总价格
    selectedPrice(state) {
        return state.cartList?.filter(item => item.selected).reduce((sum, cur) => sum + cur.count * cur.price, 0) || 0;
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters,
}
